package com.haiheng.voiceandbook

import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import androidx.viewpager2.widget.ViewPager2
import com.haiheng.bookmusic.base.BaseActivity
import com.haiheng.library.log.LogUtils
import com.haiheng.voiceandbook.adapter.ImagePagerAdapter
import com.haiheng.voiceandbook.databinding.ActivityScreenSaverBinding
import java.io.File
import java.util.Timer
import java.util.TimerTask

/**
 *
 * @Des:屏保页面
 * @Author: hwz
 * @Date:2023/12/19 0019
 * @Version: 1.0
 */
class ScreenSaverActivity : BaseActivity() {

    private lateinit var binding: ActivityScreenSaverBinding
    private lateinit var viewPager: ViewPager2
    private lateinit var imagePaths: ArrayList<String> // 存储本地图片路径的列表
    private var currentPage = 0
    private val handler = Handler()
    private  var timer: Timer? = null
    companion object {
        private const val DELAY_MS: Long = 3000 // 切换图片的延迟时间（毫秒）
        private  var PERIOD_MS: Long = Constants.getSreenSaverPicTime()*1000L // 切换图片的周期时间（毫秒）
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 检查当前是否已经在屏保页面，如果是则不再创建新实例
        if (!isTaskRoot && intent.hasCategory(Intent.CATEGORY_LAUNCHER)
            && intent.action != null && intent.action == Intent.ACTION_MAIN) {
            LogUtils.d("当前是已经在屏保页面，如果是则不再创建新实例")
            finish()
            return
        }


    }

    override fun initDataChange() {

    }

    override fun initListener() {

    }

    override fun initData() {

    }

    override fun initView() {
        viewPager = binding.viewPager
        // 从设备根目录中获取 ScreenPic 文件夹下的图片路径
        try {
//            val screenPicFolder = File("/ScreenPic") // 假设ScreenPic文件夹在设备根目录下
            val screenPicFolder = File(Environment.getExternalStorageDirectory(),Constants.SCREEN_SAVER_FILE_NAME)
            if (screenPicFolder.exists() && screenPicFolder.isDirectory) {
                val files = screenPicFolder.listFiles()
                if (files != null && files.isNotEmpty()) {
                    imagePaths = ArrayList()
                    for (file in files) {
                        if (file.isFile && file.extension in arrayOf("jpg", "jpeg", "png")) {
                            imagePaths.add(file.absolutePath)
                        }
                    }
                    if (imagePaths.isNotEmpty()) {
                        // 添加图片路径到列表中
                        val adapter = ImagePagerAdapter(imagePaths)
                        viewPager.adapter = adapter
                        // 开始定时切换图片
                        timer = Timer()
                        timer?.schedule(object : TimerTask() {
                            override fun run() {
                                handler.post {
                                    if (currentPage == imagePaths.size) {
                                        currentPage = 0
                                    }
                                    viewPager.currentItem = currentPage++
                                }
                            }
                        }, DELAY_MS, PERIOD_MS)

                    }
                }
            }

        }catch (ex:Exception){
            LogUtils.e("获取屏保异常："+ex)
            finish()
        }
        binding.vContent.setOnClickListener {
            finish()
        }
    }

    override fun intiLayout() {
        binding = ActivityScreenSaverBinding.inflate(LayoutInflater.from(this))
        setContentView(binding.root)
    }

    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel() // 在页面销毁时取消定时器
    }
}